layui.define(['table', 'form', 'laydate', 'dropdown', 'public', 'util', 'table_card', 'tableMerge','cascader'], function (exports) {
    "use strict";
    let cascaderData={};
    let InitConfig = function (data, code) {
        let InitData = {};
        let menuarr = [];
        data.forEach((item, index) => {
            data[index]['on'] = false;
            if (item.code == code) {
                data[index]['on'] = true;
                let table = item.table;
                let header = item.header;
                InitData = {
                    header: header,
                    table: table,
                    left: item.left || {},
                    url: item.url
                };
            }
        })
        return InitData;
    }


    let TplShow = function (data) {
        layui.public.ViewTpl(data, 'view_body_data', 'view_body');
        let search = data.header.search || [];
        if (search.length) {
            layui.rnform.GetForm(search, '.table_from');
            search.forEach((item, index) => {
                let width = item.width || '';
                if (width) {
                    $('.table_from .design-box').eq(index).css('width', width)
                }
                $('.table_from .design-box').eq(index).attr('class', 'design-box table_from_item')
            })
        }
        LeftData();
    }

    let ColsAll = function (cols = [], tableid = '') {
        cols.forEach((item, index) => {
            let update = item.update || '';
            let field = item.field || '';
            let options = item.options || '';
            let tpl = item.tpl || '';
            let search = item.search || '';
            let desc = item.desc || '';
            let title = '';
            let select_title = '';
            let z = 1;
            let str = '';
            let required = item.required || '';
            if (tpl) {
                str += $(tpl).html();
            }
            if (field == 'create_id' && tpl == "") {
                str += '{{- d.create_name}}';
            }
            if (field == 'update_id' && tpl == "") {
                str += '{{- d.update_name}}';
            }

            if (required == 1) {
                item['title'] = '<span class="layui-form-item-required"></span>' + item['title'];
            }
            if (update && tpl == "") {
                str += '{{- layui.engine_table.UpdateHtml(d,"' + field + '","' + update + '","' + tableid + '") }}';
            }
            if (options && tpl == '' && field != 'update_id' && field != 'create_id' && update=='') {
                str += '<span class="status_con bg_color_{{d.' + field + '}}">{{= layui.engine_table.GetSource(d.' + field + ',"' + field + '","' + tableid + '") }}</span>';
            }
            if (str) {
                cols[index]['templet'] = str;
            }

            if (desc == 1) {
                title += '<li class="layui-table-sort layui-inline">' + '<i class="table-sort-val layui-edge layui-table-sort-asc" title="升序" data-id="asc" data-val="' + item['field'] + ' asc" data-table="' + tableid + '" onclick="layui.engine_table.GetSort(this)"></i>' + '<i class="table-sort-val layui-edge layui-table-sort-desc" title="降序" data-id="desc" data-val="' + item['field'] + ' desc" data-table="' + tableid + '" onclick="layui.engine_table.GetSort(this)"></i>' + '</li>';
                z = 2;
            }
            if (search == 'select') {
                select_title = '<li data-table="' + tableid + '" id="' + item['field'] + '" class="table_search" onclick="layui.engine_table.GetSelect(this)"><i class="ruinuo-icon icon-filter"></i></li>';
                z = 2;
            }
            if (z == 2) {
                let newtitle = '<div class="display_flex table_title">';
                newtitle += '<li class="flex_1" id="title_' + item['field'] + '" data-title="' + item['title'] + '">' + item['title'] + '</li>';
                if (title) {
                    newtitle += title;
                }
                if (select_title) {
                    newtitle += select_title;
                }
                newtitle += '</div>';
                cols[index]['title'] = newtitle;
            }


        })
        return cols;
    }
    let UpdateHtml = function (data = [], field = '', action = '', tableelem = '') {

        let str = '';
        let value = data[field] || '';
        switch (action) {
            case "switch":
                let checked = '';
                if (value == 1) {
                    checked = 'checked';
                }
                str += '<input type="checkbox" name="' + field + '" value="' + value + '" lay-skin="switch" lay-text="是|否" lay-filter="edit_table_switch" ' + checked + '/>';
                break;
            case "input":
                str += '<input name="' + field + '" placeholder="请输入" class="layui-input" value="' + value + '" onBlur="layui.engine_table.EditInput(this)">';
                break;
            case "date":
            case "time":
                str += '<input name="' + field + '" class="layui-input table_lay' + action + '" readonly placeholder="选择日期" value="' + value + '">';
                break;
            case "select":
                //value = layui.engine_table.GetSource(value, field, tableelem);
                //str += '<div class="ruinuo_relative" lay-submit="" lay-filter="SelectShow" data-field="' + field + '"><input name="' + field + '" class="layui-input table-dropdpwn" readonly placeholder="请选择" value="' + value + '"></div>';
               // str += '<input name="' + field + '" data_table="'+tableelem+'" class="layui-input cascader_select" readonly placeholder="请选择" value="' + value + '">';
                let newData = SourceData(tableelem, field);
                str+='<select name="' + field + '" lay-filter="SelectShow" lay-search="">';
                str+='<option value="">请选择</option>';
                str+=layui.engine_form.SelectOption(newData,value);
                str+='</select>';
                break;
        }

        return str;
    }




    let EditDate = function () {
        layui.laydate.render({
            elem: '.table_laydate',
            done: function (value, date, endDate) {
                let res = layui.table.getRowData(this.elem);
                let postdata = {};
                let tableelem = res.id || '';
                let data = res.data;
                let id = data.id || '';
                let field = $(this.elem).attr('name');
                data[field] = value;
                let dataBak = layui.table.cache[tableelem];

                if (id) {
                    postdata = {id: id, field: field, value: value};
                }
                layui.engine_table.EditAction(dataBak, tableelem, postdata);
            }
        });
        layui.laydate.render({
            elem: '.table_laytime',
            type: 'datetime',
            fullPanel: true,
            done: function (value, date, endDate) {
                let res = layui.table.getRowData(this.elem);
                let postdata = {};
                let tableelem = res.id || '';
                let data = res.data;
                let id = data.id || '';
                let field = $(this.elem).attr('name');
                data[field] = value;
                let dataBak = layui.table.cache[tableelem];
                if (id) {
                    postdata = {id: id, field: field, value: value};
                }
                layui.engine_table.EditAction(dataBak, tableelem, postdata);
            }
        });
    }

    let EditSelect = function () {
        layui.form.on('select(SelectShow)', function (obj) {
            let elem = obj.elem;
            let field = $(elem).attr('name');
            let res = layui.table.getRowData(elem);
            let tableelem = res.id || '';
            res.data[field] = obj.value;
            let dataBak = layui.table.cache[tableelem];
            let postdata = {};
            let id = res.data.id || '';
            if (id) {
                postdata = {id: id, field: field, value:res.data[field]};
            }
            layui.engine_table.EditAction(dataBak, tableelem, postdata);
        })

        layui.form.on('submit(SelectShow)', function (obj) {
            let elem = obj.elem;
            let field = $(elem).attr("data-field");
            let res = layui.table.getRowData(elem);
            let tableelem = res.id || '';
            let id = res.data.id || '';
            let newData = SourceData(tableelem, field);
            let array = [];
            array.push({value: '', label: '请选择'});
            newData.forEach(item => {
                array.push(item);
            })
            layui.dropdown.render({
                elem: elem,
                show: true,
                data: array,
                accordion: true,
                customName: {
                    id: 'value',
                    title: 'label',
                    children: 'children'
                },
                click: function (data, othis) {

                    if (data.label == '请选择') {
                        $(elem).find("input").val('');
                    } else {
                        $(elem).find("input").val(data.label);
                    }
                    res.data[field] = data.value;
                    let dataBak = layui.table.cache[tableelem];
                    let postdata = {};
                    if (id) {
                        postdata = {id: id, field: field, value: data.value};
                    }
                    layui.engine_table.EditAction(dataBak, tableelem, postdata);
                }
            });
        })
    }

    let EditSwitch = function () {
        layui.form.on('switch(edit_table_switch)', function (obj) {
            let res = layui.table.getRowData(obj.elem);
            let tableelem = res.id || '';
            let id = res.data.id || '';
            if (obj.elem.checked) {
                res.data[obj.elem.name] = 1;
            } else {
                res.data[obj.elem.name] = 2;
            }
            let dataBak = layui.table.cache[tableelem];
            let postdata = {};
            if (id) {
                postdata = {id: id, field: obj.elem.name, value: res.data[obj.elem.name]};
            }
            layui.engine_table.EditAction(dataBak, tableelem, postdata);
        })
    }

    let GetSource = function (value = '', field = '', tableelem = 'datatable') {

        if (value || value == 0) {
            let list = SourceData(tableelem, field);
            value = layui.engine_table.SourceList(value, list)
        }
        return value;
    }
    let SourceList = function (value = '', list = []) {
        value = '' + value + '';
        let val = '';
        for (let k = 0; k < list.length; k++) {
            let children=list[k].children || [];
            if (children.length!=0)
            {
                val +=SourceList(value,children);
            }
            let item = value.split(',');
            for (let kk = 0; kk < item.length; kk++) {
                if (item[kk] == list[k].value) {
                    val += list[k].label + ',';
                }
            }
        }
        return val.replace(/,([^,]*)$/, "$1");
    }

    let SourceData = function (tableelem = '', field = '') {

        let cols = [];
        let table = SettingData[tableelem]['table'] || '';
        if (table) {
            cols = SettingData[tableelem]['table']['cols'] || [];
        } else {
            cols = SettingData[tableelem]['cols'] || [];
        }
        let datas = [];
        let more = cols[0].length || '';
        if (more != "") {
            let NewCols = [];
            cols.forEach(item => {
                item.forEach(item2 => {
                    NewCols.push(item2);
                })
            })
            cols = NewCols;
        }
        cols.forEach(item => {
            let field_d = item.field || '';
            if (field_d == field) {
                if (item.options) {
                    datas = SettingData[tableelem]['source'][item.options] || [];
                }
            }
        })
        return datas.rows || [];
    }


    let EditInput = function (obj) {
        let res = layui.table.getRowData(obj);
        let tableelem = res.id || '';
        let data = res.data;
        let id = data.id || '';
        let field = $(obj).attr('name');
        data[field] = $(obj).val();
        let dataBak = layui.table.cache[tableelem];
        let postdata = {};
        if (id) {
            postdata = {id: id, field: field, value: data[field]};
        }
        layui.engine_table.EditAction(dataBak, tableelem, postdata);
    }


    let EditAction = function (arr = [], tableelem = '', postdata = '') {
        let id = tableelem.replace("table", "focus");
        let value = JSON.stringify(arr);
        $('#' + id).val(value);
        let config = SettingData[tableelem] || [];
        let table = config['table'] || [];
        let update = table['update'] || '';
        switch (tableelem) {
            case "design_table_elem":
                layui.design_table.EditCols(arr);
                break;
            default:
                if (update && postdata) {
                    layui.http.SendAjax(update, postdata, [], function (res) {
                        if (res.code != 200) {
                            layer.msg(res.msg, {icon: 2});
                        } else {
                            layer.msg('修改成功', {icon: 1});
                        }
                    })
                }
                TableGongShi(config);
        }
    }


    let ColsUnshift = function (arr = [], cols) {
        let choose = layui.public.GetQuery("choose") || '';
        let data = {};
        let type = '';
        arr.forEach(item => {
            let url = item['url'] || '';
            let length = url.split('}').length;
            if (length >= 2) {
                choose = 1;
            }
        })
        if (choose == 1) {
            data = {type: 'checkbox', Width: 70};
            cols.unshift(data);
            type = 'checkbox';
        }
        if (choose == 2) {
            data = {type: 'radio', Width: 70};
            cols.unshift(data);
            type = 'radio';
        }
        if (type) {
            layui.table.on('row(datatable)', function (obj) {
                obj.setRowChecked({
                    type: type
                });
            });
        }
        return cols;
    }


    let ColsButton = function (arr = [], cols) {
        let button = '';
        let width = 0;
        let drop = 2;
        let title = '';
        arr.forEach((item, index) => {
            let btn_class = item['btn_class'] || '';
            let icon = item['icon'] || '';
            title = item['title'] || '';
            let is_drop = item['is_drop'] || 2;
            let where = item['where'] || '';
            where = layui.public.ChangeSql(where);
            console.log(where);
            if (is_drop == 2) {
                if (where) {
                    button += '{{#  if(' + where + '){ }}';
                }
                button += '<button  class="pear-btn pear-btn-smm ' + btn_class + '" data-index="' + index + '" lay-event="table_button" >';
                if (icon) {
                    button += '<i class="ruinuo-icon ' + icon + '" title="' + title + '"></i>';
                    width = width + 55;
                } else {
                    button += '<span style="font-size: 12px">' + title + '</span>';
                    width = width + Number(title.length) * 20 + 30;
                }
                button += '</button>';
                if (where) {
                    button += '{{#  } }}';
                }

            } else {
                drop = 1;
            }
        })
        if (drop == 1) {
            title = "更多";
            button += '<button class="pear-btn pear-btn-smm btn_theme_6" lay-event="table_dropdown" >';
            button += '<span style="font-size: 12px">' + title + '</span>';
            width = width + Number(title.length) * 20 + 30;
            button += '</button>';
        }
        if (button) {
            let data = {title: '操作', width: width, fixed: 'right', templet: '<div>' + button + '</div>'};
            cols.push(data);
        }
        HeadDropdown();
        return cols;
    }

    let TableStyle = function (table, data = []) {
        let style = table.style || 1;
        switch (Number(style)) {
            case 2://多行表格
                table['lineStyle'] = table['lineStyle'] || 'height: auto;';
                GeneralTable(table, data);
                break;
            case 3://树形表格
                TreeTable(table, data);
                break;
            case 4://卡片表格
            case 5://图文表格
                TableCard(table, data);
                break;
            default:
                GeneralTable(table, data);
        }
    }


    let TableConfig = function (table, data = []) {
        let elem = table.elem;
        let token = localStorage.getItem('token') || '';
        let lineStyle = table.lineStyle || '';
        let url = table.url || '';
        let height = table.height || '';
        let page = table.page || false;
        let limit = table.limit || 0;
        let cols = table.cols || [];
        let style = table.style || 1;
        let more = cols[0].length || '';
        if (more == '') {
            cols = [cols];
        }
        let parent_id = table.parent_id || 'parent_id';
        let config = {
            elem: '#' + elem,
            height: height,
            method: 'post',
            loading: true,
            url: url,
            where: TableWhere(),
            lineStyle: lineStyle,
            autoSort: false,
            //skin:'line',
            page: page, //开启分页
            limits: [10, 30, 50, 100, 200, 300, 500],
            limit: limit,
            cols: cols, //表头
            even: true,
            data: data,
            headers: {token: token},
            cellExpandedMode: 'tips',
            parseData: function (res) {
                layer.closeAll('loading');
                if (res.code == 201) {
                    layer.confirm('系统监测到您还没有登录', function (index) {
                        window.open("/admin/index/login/", '_top')
                    })
                    return;
                }
                if (res.code != 200) {
                    layer.alert(res.msg, {icon: 2})
                }
                let back = res.data || {}
                let total = back.total || 0;
                let rows = back.rows || [];
                if (style == 3) {
                    rows = TreeTableData(rows, parent_id);
                }
                let urlsData = layui.public.GetQueryAll() || {};
                rows.forEach(item => {
                    $.each(item, function (key, res) {
                        let t1 = item[key] || '';
                        let val = urlsData['choose_' + key] || 'no_choose_';
                        let vals = val.split(',');
                        vals.forEach(t2 => {
                            if (t1 == t2) {
                                item['LAY_CHECKED'] = true;
                                console.log(1);
                            }
                        })
                    })
                });
                return {"code": 0, "msg": "OK", "count": total, "data": rows}
            },
            done: function (res) {
                let options = this;
                layui.table.getRowData = function (elem) {
                    options.id = $(elem).closest('div.layui-table-view').attr('lay-id');
                    let index = $(elem).closest('tr').data('index');
                    let data = layui.table.cache[options.id][index] || {};
                    return {id: options.id, data: data};
                };
                TableBar(options.id);
                EditDate();
                EditSelect();
                EditSwitch();
                SelectTitle();
                DragSort(options.id, res.data);
                TableTrStyle(options.id, res.data);
            }

        };
        return config;
    }
    let GeneralTable = function (table, data = []) {
        let options = TableConfig(table, data);
        layui.table.render(options);
    }
    let TreeTable = function (table, data = []) {
        let options = TableConfig(table, data);
        let parent_id = table.parent_id || 'parent_id';
        let parent_name = table.parent_name || 'title';
        options['page'] = false;
        options['tree'] = {
            customName: {
                name: parent_name,
                pid: parent_id,
                icon: ''
            },
            view: {
                expandAllDefault: true,
            },
        };
        layui.treeTable.render(options);
    }
    let TreeTableData = function (arr = [], field = 'parent_id', parent_id = 0) {
        let lists = [];
        arr.forEach(item => {
            if (item[field] == parent_id) {
                let child = TreeTableData(arr, field, item.id);
                if (child.length != 0) {
                    item['children'] = child;
                }
                lists.push(item);
            }
        });
        return lists;
    }


    let TableCard = function (table, data) {
        if ($(".card_table").length == 0) {
            $(".table_view").append("<div class='card_table'></div>")
        }
        let where = TableWhere();
        where.limit = table.limit;
        layui.table_card.render({
            cols: table.cols,
            url: table.url,
            where: where,
            colMd: 3,
            parseData: function (res) {
                return {records: res.data.rows, total: res.data.total};
            },
            toolbar: '#barMenu',
            method: 'post',
            contentType: true,
            multiSortSwitch: true,
            elem: ".card_table"
        });
    }

    let TableWhere = function () {
        let PostData = layui.public.GetQueryAll() || {};//筛选
        let item = SeleteData || [];
        $.each(item, function (key, res) {
            let value = res['value'] || '';
            if (value) {
                PostData[key] = value;
            }
        })

        $(".table_from_item *[name]").each(function () {//搜索
            let name = $(this).attr("name");
            let value = $(this).val();
            if (value) {
                PostData[name] = value;
            }
        });

        PostData['raw'] = raw || '';
        PostData['menu_code'] = menu_code || '';

        return PostData;
    }

    let TableBar = function (tableelem = '') {
        layui.table.on('tool(' + tableelem + ')', function (obj) {
            let layEvent = obj.event;
            let that = this;
            let index = $(that).attr('data-index') || 0;
            let rows = obj.data;
            let button = InitData['table']['button'] || [];
            let dropdown = [];
            button.forEach((item, index) => {
                if (item.is_drop == 1) {
                    dropdown.push({id: index, title: item.title});
                }
            });
            switch (layEvent) {
                case "table_button":
                    ButtonAciton(index, 2, tableelem, rows)
                    break;
                case "table_dropdown":
                    layui.dropdown.render({
                        elem: that,
                        show: true,
                        data: dropdown,
                        click: function (data, othis) {
                            ButtonAciton(data.id, 2, tableelem, rows)
                        },
                        align: 'right', // 右对齐弹出
                        style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
                    })
                    break;
            }
        });
    }

    let ButtonAciton = function (index = 0, type = 1, tableelem = '', d = []) {
        let data = [];

        switch (type) {
            case 1:
                data = SettingData[tableelem]['header']['button'][index] || [];
                break;
            case 2:
                data = SettingData[tableelem]['table']['button'][index] || [];
                break;
        }

        let url = data['url'] || '';
        if (url.includes('outexcel')) {
            url = url + '?' + layui.public.formateObjToParamStr(TableWhere());
            layer.confirm('确定要导出数据吗？', function (index) {
                layer.close(index);
                window.location.href = url;
            })
            return false;
        }
        if (url.includes('inexcel')) {

            let urls = url.split('/');
            layui.public.OpenWindow('/common/component/excel/?app_num=' + urls[1] + '&mode_num=' + urls[2], '导入');
            return false;
        }
        let title = data['title'] || '';
        let width = data['width'] || '0';
        let height = data['height'] || '0';
        let length = url.split('}').length;
        if (Number(length) >= 2 && Number(type) == 1) {
            let checkStatus = layui.table.checkStatus('' + tableelem + '');
            let checkStatusdata = checkStatus.data;
            if (checkStatusdata.length === 0) {
                layer.msg("未选中数据", {icon: 2});
                return false;
            }
            var ids = "";
            for (var i = 0; i < checkStatusdata.length; i++) {
                ids += checkStatusdata[i].id + ",";
            }
            d['id'] = ids.substr(0, ids.length - 1);
        }
        url = layui.public.GetUrl(d, url);

        switch (data['type']) {
            case "window":
                url += "&elem=" + tableelem;
                layui.public.OpenWindow(url, title, width, height);
                break;
            case "ajax":
                layui.public.OpenAjax(url, title, "layui.engine_table.SearchLoad(\"" + tableelem + "\",1);");
                break;
            case "open":
                window.location.href = url;
                break;
            case "js":
                window.location.href = url;
                break;
            case "url":
                window.location.href = url;
                break;
        }
    }

    let SearchLoad = function (elem = '', type = '') {
        elem = elem || 'datatable';
        let config = SettingData[elem] || [];
        let table = config.table || '';
        if (table == "") {
            table = config;
        }
        let page = table.page || false;
        LoadSum(config);
        if (type && page) {
            $(".layui-laypage-btn").click();//只刷新当前页
            return false;
        }
        TableStyle(table);

    }

    let SearchBack = function (elem = '') {
        elem = elem || 'datatable';
        let config = SettingData[elem] || [];
        let table = config.table || [];
        SeleteData = {}
        $('.table_from_item .layui-input').val("");
        $('.table_from_item select').find("option:selected").attr("selected", false);
        TableStyle(table);
    }

    let TableMenu = function (obj) {
        $(".head_menu li").removeClass("on");
        $(obj).addClass("on");
        menu_code = $(obj).attr('data-code');
        onLoad();
    }
    let GetSort = function (obj) {
        raw = $(obj).attr("data-val");
        let elem = $(obj).attr('data-table');
        SearchLoad(elem);
    }

    let SelectTitle = function () {
        $(".table_search").each(function () {
            var field = $(this).attr("id");
            var item = SeleteData[field] || [];
            var value = item['value'] || '';
            var title = $("#title_" + field).attr('data-title') || '';
            var data_title = item['label'] || '';

            if (value) {
                $("#title_" + field).html(data_title);
                $("#title_" + field).parent(".table_title").parent("span").parent("div").addClass("table_title_on");
            } else {
                $("#title_" + field).html(title);
                $("#title_" + field).parent(".table_title").parent("span").parent("div").removeClass("table_title_on");
            }
        });
    }

    let GetSelect = function (obj) {//表格筛选

        let field = $(obj).attr('id');
        let elem = $(obj).attr('data-table');
        let newData = SourceData(elem, field);
        console.log(newData);
        let array = [];
        array.push({value: '', label: '全部'});
        newData.forEach(item => {
            array.push(item);
        })

        layui.dropdown.render({
            elem: obj,
            show: true,
            data: array,
            customName: {
                id: 'value',
                title: 'label',
                children: 'children'
            },
            align: 'right',
            style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);',
            click: function (data, othis) {
                SeleteData[field] = data;
                SearchLoad(elem);
            }
        });
    }

    let GetLeftHtml = function (rows = []) {
        let left = InitData.left || {};
        let type = left.type || 1;
        let show_field = left.show_field;
        let key_field = left.key_field;
        let html = '';
        let icon = '';
        rows.forEach((item, index) => {
            let children = item.children || [];
            if (children.length == 0) {
                html += '<li  data-id="' + item[key_field] + '" data-table="" onclick="layui.engine_table.LeftClick(this);">';
                html += '<div class="layui-menu-body-title">' + item[show_field] + '</div>';
                if (type == 2) {
                    html += '<div class="ruinuo_more ruinuo-icon icon-elipsis"></div>';
                }
                html += '</li>';
            } else {
                if (index != 0) {
                    icon = '<i class="layui-icon layui-icon-down"></i>';
                    html += '<li lay-options="{rn_mid:' + item[key_field] + ',type: \'group\'}" class="layui-menu-item-group layui-menu-item-up">';
                } else {
                    icon = '<i class="layui-icon layui-icon-up"></i>';
                    html += '<li lay-options="{rn_mid:' + item[key_field] + ',type: \'group\'}" class="layui-menu-item-group layui-menu-item-down">';
                }
                html += '<div class="layui-menu-body-title" style=" font-weight: bold;color:#000;">' + item[show_field] + '' + icon + '</div>';
                html += '<ul>';
                html += GetLeftHtml(children);
                html += '</ul></li>';
            }
        });
        return html;
    }

    let LeftData = function () {
        let left = InitData.left || {};
        let status = left.status || 2;
        if (Number(status) == 1) {
            let type = left.type || 1;
            let postData = {page: 1, limit: 0};
            layui.http.SendAjax(left['url']['list'], postData, [], function (res) {
                let rows = res.data.rows || [];
                let html = '';
                html += '<li  data-id="" data-table="" class="layui-menu-item-checked" onclick="layui.engine_table.LeftClick(this);">';
                html += '<div class="layui-menu-body-title">全部</div>';
                html += '</li>';
                html += GetLeftHtml(rows);
                $(".left .layui-menu ul").html(html);
                if (type == 2) {
                    let width = left.url.width || 0;
                    let height = left.url.height || 0;
                    let onclickData = [
                        {
                            title: '修改',
                            open: 'window',
                            url: left['url']['edit'] + '?id={id}',
                            width: width,
                            height: height
                        },
                        {
                            title: '删除',
                            open: 'ajax',
                            url: left['url']['delete'] + '?id={id}',
                            onclick: 'layui.engine_table.LeftData()',
                        },
                    ];
                    layui.public.DropdownInit('.ruinuo_more', 'hover', onclickData);
                    let addOnclick = "layui.public.OpenWindow('" + left['url']['add'] + "', '新增', '" + width + "', '" + height + "');";
                    $(".tree_add").attr("onclick", addOnclick);
                }
            })
        }
    }

    let LeftClick = function (obj) {
        let value = $(obj).attr('data-id') || '';
        let elem = $(obj).attr('data-table') || '';
        $(".left_value").val(value);
        SearchLoad(elem);
    }
    let DragSort = function (elem, res = []) {
        try {
            let length = $('.' + elem + ' tbody').length;
            if (length == 0) {
                return false;
            }
            let tbody = document.querySelector('.' + elem + ' tbody');
            let sortable = Sortable.create(tbody, {
                group: {
                    name: 'propertygroup',
                },
                ghostClass: "ghost",
                handle: '.ruinuo-drag',
                dataIdAttr: 'data-index',
                animation: 150,
                onEnd: function (evt) {
                    let arr = sortable.toArray();
                    let dataBak = [];
                    for (let k = 0; k < arr.length; k++) {
                        dataBak.push(res[arr[k]])
                    }
                    layui.table.reload(elem, {
                        data: dataBak, url: '',
                    })
                    layui.engine_table.EditAction(dataBak, elem);
                }
            });
        } catch (err) {
            console.log(err)
        }
    }
    let LoadSum = function (config = {}) {

        let tag = config.tag || '';
        if (tag) {
            return [];
        }
        let url = config.url || '';
        let PostData = TableWhere();
        PostData.tabs = 2;
        layui.http.SendAjax(url, PostData, [], function (res) {
            let menu = res.data.menu || [];
            menu.forEach(item => {
                $("#menu_" + item.code).text(item.num);
            });
            let total = res.data.total || [];
            total.forEach(item => {
                $("#total_" + item.code).text(item.num);
            });
        })
    };

    /*新增数据表格*/
    let AddTable = function (tableelem) {
        var dataBak = [];
        var tableBak = layui.table.cache[tableelem];
        for (var i = 0; i < tableBak.length; i++) {
            dataBak.push(tableBak[i]);
        }
        dataBak.push({});
        layui.table.reload(tableelem, {
            data: dataBak, url: '',
        })
        EditAction(dataBak, tableelem);
    }
    /*删除数据表格*/
    let DeleteTable = function (tableelem = '', index = 0) {
        var dataBak = [];
        var tableBak = layui.table.cache[tableelem];
        for (var i = 0; i < tableBak.length; i++) {
            if (i != index) {
                dataBak.push(tableBak[i]);
            }
        }
        layui.table.reload(tableelem, {
            data: dataBak, url: '',
        })
        EditAction(dataBak, tableelem);
    }

    let ChooseTable = function (elem_id) {
        let name = $("#focus_" + elem_id).attr('name');
        let nameVal = $("#focus_" + elem_id).val() || '';
        let url = $("#open_" + elem_id).attr('data_url');
        let rule = $("#open_" + elem_id).attr('data_rule');
        let rules = rule.split(',');
        let urlname = name;
        rules.forEach(item => {
            let c = item.split('||');
            if (c[0] == name) {
                urlname = c[1];
            }
        })
        let tag = $("#open_" + elem_id).attr('data_tag');
        if (tag == 'jsontable') {
            urlname = "id";
            nameVal = '';
            let nameVals = $("#focus_" + elem_id).val() || '[]';
            nameVals = eval(nameVals);
            nameVals.forEach(item => {
                let choose_id = item.choose_id || '';
                if (choose_id) {
                    nameVal += choose_id + ',';
                }
            })
            nameVal = nameVal.substr(0, nameVal.length - 1);
        }
        url = url + '&choose_' + urlname + '=' + nameVal;
        let choose = 2;
        if (url.includes('choose=1')) {
            choose = 1;
        }
        parent.layer.open({
            type: 2,
            offset: 'auto',
            title: '选择',
            area: ['90%', '90%'],
            scrollbar: true,
            content: url,
            btnAlign: 'r',
            btn: ['确定', '取消'],
            shade: 0.3,
            yes: function (index) {
                let iframe = parent.window['layui-layer-iframe' + index];
                let backData = iframe.layui.engine_table.getChooseData() || false;
                if (backData == false) {
                    return false;
                }
                switch (tag) {
                    case "jsontable":
                        let tableelem = 'table_' + elem_id;
                        let newData = $("#focus_" + elem_id).val() || '[]';
                        newData = eval(newData);
                        if (choose == 2) {
                            newData = [];
                        }
                        backData.forEach(val => {
                            let vals = {};
                            vals['choose_id'] = val.id || 0;
                            let del = layui.public.ArrayDelMoer(newData, vals['choose_id'], 'choose_id');
                            if (del == 2) {
                                rules.forEach(item => {
                                    let c = item.split('||');
                                    vals[c[0]] = val[c[1]] || '';
                                })
                                newData.push(vals);
                            }
                        })
                        layui.table.reload(tableelem, {
                            data: newData, url: '',
                        })

                        $("#focus_" + elem_id).val(JSON.stringify(newData));
                        break;
                    case "choosetable":
                        let vals = nameVal.split(',')
                        backData.forEach(val => {
                            let t = '' + val['id'] + '';
                            vals.push(t);
                        })
                        let uniqueArr = Array.from(new Set(vals));
                        if (choose == 2) {
                            uniqueArr = [backData[0]['id']];
                        }
                        let ids = uniqueArr.filter(item => item !== null && item !== undefined && item !== '').join(',');
                        $("#focus_" + elem_id).val(ids);
                        layui.engine_form.ChooseTableInit(elem_id);
                        break;
                    case "openselect":
                        rules.forEach(item => {
                            let c = item.split('||');
                            let save_field = c[0];
                            let show_field = c[1];
                            let indexVal = $("input[name='" + save_field + "'],select[name='" + save_field + "'],textarea[name='" + save_field + "']").val() || '';
                            let vals = indexVal.split(',');
                            backData.forEach(val => {
                                let t = '' + val[show_field] + '';
                                vals.push(t);
                            })
                            let uniqueArr = Array.from(new Set(vals));
                            if (choose == 2) {
                                uniqueArr = [backData[0][show_field]];
                            }
                            let values = uniqueArr.filter(item => item !== null && item !== undefined && item !== '').join(',');
                            $("input[name='" + save_field + "'],select[name='" + save_field + "'],textarea[name='" + save_field + "']").val(values);
                        })
                        layui.engine_form.BindOpenSelect(elem_id);
                        break;
                }
                let bindex = parent.layer.getFrameIndex('layui-layer-iframe' + index);
                parent.layer.close(bindex);
            }
        })
    }

    let getChooseData = function () {
        var checkStatus = layui.table.checkStatus('datatable');
        var checkStatusdata = checkStatus.data;
        if (checkStatusdata.length === 0) {
            layer.msg("未选中数据", {icon: 2});
            return false;
        }
        return checkStatusdata;
    }
    let SplitValue = function (value = '') {
        let str = value || '';
        return str.split(',');
    }

    let HeadDropdown = function () {
        let button = InitData['header']['button'] || [];
        let dropdown = [];
        button.forEach((item, index) => {
            if (item.is_drop == 1) {
                dropdown.push({id: index, title: item.title});
            }
        });
        let table_elem = InitData['table']['elem'];
        layui.dropdown.render({
            elem: ".head_more_button"
            , data: dropdown
            , click: function (data, othis) {
                ButtonAciton(data.id, 1, table_elem)
            },
            align: 'left',
            style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);'
        })
    }

    let TableLoadData = function () {
        raw = '';//排序
        SeleteData = {};
        let copyArr = $.extend(true, [], table_config);
        InitData = layui.engine_table.InitConfig(copyArr, menu_code);
        let PostData = layui.public.GetQueryAll() || {};
        PostData.menu_code = menu_code;
        let data = {
            PostData: PostData
        }
        return data;
    }
    let TableLoadBack = function (res) {
        InitData['source'] = res.data.source || {};
        InitData['header']['menu'] = res.data.menu || [];
        InitData['header']['total'] = res.data.total || [];
        InitData['header']['button'] = res.data.head_button || [];
        InitData['table']['button'] = res.data.table_button || [];
        layui.engine_table.TplShow(InitData);//初始化页面
        let DataHeader = InitData.header || [];
        let DataTable = InitData.table || [];
        let cols = layui.engine_table.ColsAll(DataTable.cols, DataTable.elem);
        cols = layui.engine_table.ColsUnshift(DataHeader.button, cols);
        cols = layui.engine_table.ColsButton(DataTable.button, cols);
        cols = layui.engine_table.MoreTable(cols)
        DataTable.cols = cols;
        layui.engine_table.TableStyle(DataTable);
        let left_field = InitData.left.field || '';
        if (left_field) {
            $(".table_from_item").eq(0).append('<input name="' + left_field + '" class="left_value" type="hidden">');
        }
        SettingData[DataTable.elem] = InitData;
    }

    let MoreTable = function (cols = []) {
        let newCols = [];
        let groupStr = '';
        let groupCols = [];
        for (let i = 0; i < cols.length; i++) {
            let item = cols[i];
            let group = item.group || '';
            if (group) {
                groupCols.push(item);
                if (groupStr.indexOf('[' + group + ']') < 0) {
                    let colspan = ColsCount(cols, group);
                    let New = {
                        title: group,
                        align: 'center',
                        colspan: colspan,
                    };
                    if (colspan == 1) {
                        New['colGroup'] = true;
                    }
                    groupStr += '[' + group + ']';
                    newCols.push(New);
                }
                continue;
            }
            item['rowspan'] = 2;
            newCols.push(item);
        }
        if (groupCols.length >= 1) {
            let BackCols = [];
            BackCols.push(newCols);
            BackCols.push(groupCols);
            return BackCols;
        }
        return newCols;
    }
    let ColsCount = function (arr, title) {
        let t = 0;
        for (let i = 0; i < arr.length; i++) {
            if (arr[i]['group'] == title) {
                t = t + 1;
            }
        }
        return t;
    }
    let TableTrStyle = function (elem = '', arr = []) {
        arr.forEach((item, index) => {
            //$("#"+elem).next().find('tbody tr[data-index="' + index +'"]').css("background-color", "#FFA07A");
        })
    }
    let TableGongShi = function (config = {}) {
        let cols = config.cols || [];
        let elem=config.elem;
        let dataBak = layui.table.cache[elem];
        let GsItem = [];
        cols.forEach(item => {
            let gongShi = item.gongshi || '';
            let countField = item.count_field || '';

            if (gongShi || countField) {
                let aItem = {Field: item.field, gongShi: gongShi, countField: countField, gongShiArr: []};
                if (gongShi) {
                    const regex = /\{([\s\S]*?)\}/g;
                    let match;
                    while ((match = regex.exec(gongShi))) {
                        aItem.gongShiArr.push(match[1])
                    }
                }
                GsItem.push(aItem)
            }
        })
        if (GsItem.length==0)
        {
            return false;
        }

        GsItem.forEach(item => {
            let gongShiArr = item.gongShiArr || [];
            let countField = item.countField || '';
            let Field = item.Field;
            let CountVal=0;
            dataBak.forEach(val => {
                let str = item.gongShi || '';
                if (str) {
                    gongShiArr.forEach(val2 => {
                        let value = val[val2] || 0;
                        if (isNaN(value)) {
                            value=0;
                        }
                        str = str.replace("{" + val2 + "}", value);
                    })
                    let v=eval(str);
                    val[Field] =v.toFixed(2);
                }
                if (countField)
                {
                    CountVal=CountVal+Number(val[Field]);
                }
            })
            $("input[name='" + countField + "']").val(CountVal.toFixed(2));
        })
        let value = JSON.stringify(dataBak);
        let id = elem.replace("table", "focus");
        $('#' + id).val(value);
        layui.table.reload(elem, {
            data: dataBak, url: '',
        })
    }


    let EngineTable = {
        DragSort: DragSort,
        GetSelect: GetSelect,
        SelectTitle: SelectTitle,
        GetSort: GetSort,
        InitConfig: InitConfig,//配置文件初始化
        TplShow: TplShow,//页面初始化
        ColsAll: ColsAll,//表格表头
        TableBar: TableBar,//表格按钮事件触发
        ColsUnshift: ColsUnshift,//表头全选单选
        ColsButton: ColsButton,//表格按钮
        TableStyle: TableStyle,//表格风格
        GeneralTable: GeneralTable,//普通表格
        TreeTable: TreeTable,//树形表格
        TreeTableData: TreeTableData,
        TableCard: TableCard,//卡片表格
        TableWhere: TableWhere,//表格数据
        ButtonAciton: ButtonAciton,//按钮事件
        SearchLoad: SearchLoad,//开始搜索
        SearchBack: SearchBack,//搜索重置
        TableMenu: TableMenu,//菜单切换
        UpdateHtml: UpdateHtml,//编辑
        SourceData: SourceData,//获取数据源数据
        GetSource: GetSource,//获取数据源的值
        SourceList: SourceList,//数据源数据转换
        EditInput: EditInput,//文本框编辑
        EditDate: EditDate,//日期编辑,
        EditSelect: EditSelect,//下拉框编辑,
        EditSwitch: EditSwitch,//switch编辑,
        EditAction: EditAction,//保存数据
        LeftClick: LeftClick,//左侧点击
        LeftData: LeftData,//左侧数据
        GetLeftHtml: GetLeftHtml,//获取左侧HTML
        LoadSum: LoadSum,
        AddTable: AddTable,
        DeleteTable: DeleteTable,
        ChooseTable: ChooseTable,
        getChooseData: getChooseData,
        SplitValue: SplitValue,
        HeadDropdown: HeadDropdown,
        TableLoadData: TableLoadData,
        TableLoadBack: TableLoadBack,
        MoreTable: MoreTable,//多行表头，目前只支持2级
        ColsCount: ColsCount,
        TableTrStyle: TableTrStyle,//标记行颜色
        TableGongShi: TableGongShi,//公式运算
    };
    exports('engine_table', EngineTable);
});

